package com.qicheng.wlhyspider.jiangsu.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qicheng.wlhyspider.jiangsu.entity.JsDriverEntity;
import com.qicheng.wlhyspider.jiangsu.mapper.JsDriverMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/jiangsu/driver")
@Slf4j
public class JsDriverController {
    private List<String> tjDriverIdList = new ArrayList<>();

    private final JsDriverMapper jsDriverMapper;

    public JsDriverController(JsDriverMapper jsDriverMapper) {
        this.jsDriverMapper = jsDriverMapper;
    }

    @GetMapping("/save")
    public String save(@RequestParam("page") Integer page, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        Integer maxPage = 1945;
        Integer limit = 1000;
        if (CollectionUtil.isEmpty(tjDriverIdList)) {
            tjDriverIdList = jsDriverMapper.selectList(Wrappers.<JsDriverEntity>lambdaQuery()
                    .select(JsDriverEntity::getId)).stream().map(JsDriverEntity::getId).collect(Collectors.toList());
        }
        try {
            for (int i = page; i <= maxPage; i++) {
                saveAll(i, limit);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Integer pages = 2;
//        CompletableFuture<Object>[] futures = new CompletableFuture[pages];
//        for (int i = 0; i < pages; i++) {
//            int finalPage = page + i;
//            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
//                try {
//                    saveAll(finalPage,  limit);
//                    log.info("驾驶员插入，第{}页成功", finalPage);
//                } catch (Exception e) {
//                    log.error("驾驶员插入，第{}页失败", finalPage);
//                    log.error(e.getMessage(), e);
//                    e.printStackTrace();
//                }
//                return null;
//            });
//            futures[i] = future;
//        }
//        log.info("====futures.length=={}",futures.length);
//        CompletableFuture<Void> cf = CompletableFuture.allOf(futures);
//
//        // 如果执行成功:
//        cf.thenAccept((result) -> {
//            log.info("驾驶员插入成功！！！");
//            if (page < maxPage){
//                save(page + pages,startDate,endDate);
//            }
//
//        });
//        // 如果执行异常:
//        cf.exceptionally((e) -> {
//            e.printStackTrace();
//            log.info("驾驶员插入失败！！！");
//            return null;
//        });
//        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
//        try {
//            Thread.sleep(200);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "驾驶员插入成功！！！";
    }

    public String saveAll(Integer page, Integer limit) throws IOException {
        // 加载 HTML 文档
        LocalDateTime startTime = LocalDateTime.now();
        Document doc =  getDocument(page, limit);
        Duration between = Duration.between(startTime, LocalDateTime.now());
        System.out.println("查询耗时(毫秒)：" + between.getNano() / 100000);
//        System.out.println("查询耗时(秒)："+between.getSeconds());
        // 提取标题
//        Elements title = doc.select("title");

//        Elements paginate_button = doc.select(".paginate_button");

//        System.out.println(paginate_button.text());
        Elements searchDiv = doc.select("#contentTable");
        Elements trEls = searchDiv.select("tr");

        List<JsDriverEntity> list = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (int i = 1; i < trEls.size(); i++) {
            Element element = trEls.get(i);
            Elements tdEls = element.select("td");
            String s1 = tdEls.get(1).select("a").attr("onclick");
            String s2 = s1.substring("getDetail(".length(), s1.indexOf(")")).split("','")[1];
            String id = s2.substring(0, s2.length() - 1);
            JsDriverEntity jsDriverEntity = new JsDriverEntity();
            jsDriverEntity.setId(id);
            jsDriverEntity.setDriverName(tdEls.get(1).text()); // 名称
            jsDriverEntity.setGender(tdEls.get(2).text()); // 性别
            jsDriverEntity.setDrivingLicense(tdEls.get(3).text()); // 身份证号
            jsDriverEntity.setTelephone(tdEls.get(4).text()); // 手机号
            jsDriverEntity.setQualificationCertificate(tdEls.get(5).text());  // 从业资格信息证号
            jsDriverEntity.setEntName(tdEls.get(6).text()); // 所属实际承运人
            jsDriverEntity.setCreateDate(tdEls.get(7).text()); // 同步时间
            list.add(jsDriverEntity);
            ids.add(id);

        }
        if (CollectionUtils.isNotEmpty(list)) {
            list = list.stream().filter(i -> !tjDriverIdList.contains(i.getId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                jsDriverMapper.insertBatchSomeColumn(list);
                tjDriverIdList.addAll(ids);
            }
        }
        String paginationInfoText = doc.select(".pagination-info").text();
        Long count = Long.valueOf(paginationInfoText.substring(paginationInfoText.indexOf("总共 ") + 3, paginationInfoText.lastIndexOf(" 条记录")));
        log.info(String.format("驾驶员查询成功，第%s页，总页数%s", page, count / limit));

        // 输出标题
//        System.out.println(title.text());
//        System.out.println(searchDiv.html());
        return "";
    }

    private Document getDocument(Integer page, Integer limit) throws IOException {
        try {
            return Jsoup.connect("http://jswccy.3322.org:8081/jscfp/a/jscfp/query/cfcDriverinfo")
                    .cookie("JSESSIONID", "CEB091BAF2282BF1AE2734D20EE42F8D")
                    .cookie("jeesite.session.id", "717d49a50cc440e5b341aae5813fff68")
                    .cookie("pageNo", page.toString())
                    .cookie("pageSize", limit.toString())
                    .data("pageNo", page.toString())
                    .data("pageSize", limit.toString())
                    .timeout(120*1000)
                    .get();
        }catch (SocketTimeoutException e){
            e.printStackTrace();
            return getDocument(page,limit);
        }
    }


}
